<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <title></title>
</head>
<body>

<script type="text/javascript" src="../lib/socket.io.js"></script>
<script type="text/javascript">
    var socket = io.connect('http://localhost');
    socket.on('news', function (data) {
        console.log(data);
        socket.emit('my other event', { my: 'data' });
    });

    var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
    var maxPos = $chars.length
    var usr = '';
    for (i = 0; i < 6; i++) {
        usr += $chars.charAt(Math.floor(Math.random() * maxPos));
    }

    var userName=usr;

    //建立websocket连接
    socket = io.connect('http://192.168.0.23:3000');
    socket.send(userName);
    //收到server的连接确认
    socket.on('open',function(json){
        status.text(json);
    });

    //监听system事件，判断welcome或者disconnect，打印系统消息信息
    socket.on('system',function(json){
        var p = '';
        if (json.type === 'welcome'){
            if(userName==json.text) status.text(userName + ':');
            p = '系统@'+ json.time+ ':欢迎' + json.text +'!\n';

            var txt=content.val();
            content.text(txt+p);
        }else if(json.type=='userConnected')
        {
            p=json.text;
            var usrlist='';
            for(usr in p)
                usrlist=usrlist+usr+'\n';
            userlist.html(usrlist);
        }
        else if(json.type == 'disconnect'){
            p = '系统@'+ json.time+ ':再见' + json.text +'!\n';

            var txt=content.val();

            if(json.text=='false')
                return;
            else
                content.text(txt+p);
        }

    });

    //监听message事件，打印消息信息
    socket.on('message',function(json){
        var p = json.author+'@'+ json.time+ ' : '+json.text + '\n';

        var txt=content.val();
        content.html(txt+p);
    });



    //通过“回车”提交聊天信息
    input.keydown(function(e) {
        if (e.keyCode === 13) {
            var msg = $(this).val();
            if (!msg) return;
            socket.send(msg);
            $(this).val('');
            if (userName === false) {
                userName = msg;
            }
        }
    });
</script>
</body>
</html>